# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
import json
from threading import Thread

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "个人意外伤害险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 保险天数
            "days": ["1y"],
            # 保险人数
            "people_count": ["1"],
            # 意外身故和死亡
            "accident_death": ["100000", "300000", "500000"],
            # 意外伤害医疗
            "accident_medical": ["0", "10000", "50000", "100000"],
            # 住院津贴
            "accident_hospital": ["0", "50/天", "100/天", "200/天"],
            # 猝死
            "sudden_death": ["0", "500000"],
            # 救护车保险金
            "accident_ambulance": ["0", "2000"],
            # 飞机意外伤残/死亡
            "airplane_death": ["0", "3000000", "5000000"],
            # 火车意外伤残/死亡
            "train_death": ["0", "500000", "1000000"],
            # 轮船意外伤残/死亡
            "ship_death": ["0", "500000", "1000000"],
            # 汽车意外伤残/死亡
            "passenger_death": ["0", "100000", "300000", "500000"],
            # 传染病
            "accident_contagion": ["0", "100000", "200000"]
        }
        for v in product(plan["days"], plan["people_count"], plan["accident_death"], plan["accident_medical"],
                         plan["accident_hospital"], plan["sudden_death"], plan["accident_ambulance"],
                         plan["airplane_death"], plan["train_death"], plan["ship_death"], plan["passenger_death"],
                         plan["accident_contagion"]):
            data = Helper.formatProductInfo(plan, v)
            if data["sudden_death"] != "0":
                data["sudden_death"] = data["accident_death"]
            else:
                data["sudden_death"] = "0"
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):
        data = {"insurantNum": [{"personNum": "1", "subjectType": "02"}],
                "effectDate": {"addDays": "", "endDate": "2021-04-20", "beginDate": "2020-04-21"},
                "planPackage": {"marketProductCode": "MP03000581", "packageType": "01"},
                "applyPeriod": {"term": "12", "termUnit": "M"},
                "planDuty": [{"dutyCode": "CVYA001", "planCode": "PL03Y0266", "subjectType": "02",
                              "value": dt["accident_death"]},
                             {"dutyCode": "CVYB001", "planCode": "PL03Y0266", "subjectType": "02",
                              "value": "0" if dt["accident_medical"] == "0" else dt["accident_medical"]},
                             {"dutyCode": "CVJD003", "planCode": "PL03Y0266", "subjectType": "02",
                              "value": "0" if dt["accident_hospital"] == "0" else dt["accident_hospital"].replace("/天",
                                                                                                                  "")},
                             {"dutyCode": "CVJB009", "planCode": "PL03J0103", "subjectType": "02",
                              "value": "0" if dt["sudden_death"] == "0" else dt["sudden_death"]},
                             {"dutyCode": "CVJE013", "planCode": "PL03J0080", "subjectType": "02",
                              "value": "0" if dt["accident_ambulance"] == "0" else dt["accident_ambulance"]},
                             {"dutyCode": "CVYA008", "planCode": "PL03Y0197", "subjectType": "02",
                              "value": "0" if dt["airplane_death"] == "0" else dt["airplane_death"]},
                             {"dutyCode": "CVYA009", "planCode": "PL03Y0197", "subjectType": "02",
                              "value": "0" if dt["train_death"] == "0" else dt["train_death"]},
                             {"dutyCode": "CVYA010", "planCode": "PL03Y0197", "subjectType": "02",
                              "value": "0" if dt["ship_death"] == "0" else dt["ship_death"]},
                             {"dutyCode": "CVYA011", "planCode": "PL03Y0197", "subjectType": "02",
                              "value": "0" if dt["passenger_death"] == "0" else dt["passenger_death"]},
                             {"dutyCode": "CVJB017", "planCode": "PL03J0070", "subjectType": "02",
                              "value": "0" if dt["accident_contagion"] == "0" else dt["accident_contagion"]}],
                "flowId": "S0N60WitOBsIJJWi"}
        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "处理成功" in r.text:
            price = Helper.decimalParse(r.json()["quoteResult"][0]["actualPremium"])
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print( data )
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            print("\n/*产品价格更新失败:%d*/" % dt["id"])
            mysql.updateTask(data)